// pages/login/index.js
const config = require('../../utils/config');
var network = require('../../utils/network.js');
import Dialog from '../../modules/vant@1.8.0/dialog/dialog';

Page({
  /**
   * 页面的初始数据
   */
  data: {

    user: {},
    address:'',
    activeIndex:'0',
    currentCategory:{},
    categories:[],
    products:[],
    buyProductMap:{},
    buyTotalMoney:0,
    buyProductNumber:{}
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var user=wx.getStorageSync('user')
    if(!user.id){
      this.code2Session()
    }else{
      this.setData({
        user:user,
        address:wx.getStorageSync('address')
      })
      this.fetchCategory()
      this.judgeUserInfo()
    }
   
  },
  judgeUserInfo(){
    var user=wx.getStorageSync('user')
    if(!user.mobile || !user.realName){
      Dialog.alert({
        message: '为了更好的体验，请先完善用户信息（手机号、真实姓名）',
        theme: 'round-button',
      }).then(() => {
        wx.navigateTo({
          url: '/pages/user/info/index',
        })
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().init();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  code2Session(){
    wx.login({
      success: ({code}) => {
        console.log(code)
        network.getRequest(config.code2Session,{code:code},(res)=>{
          this.doLogin(res.openid)
        })
      },
    })
  },
  doLogin(openId){
    network.postRequest(config.appletLogin,openId,(res)=>{
      wx.setStorageSync('Token', res)
      this.getUserInfo()
    },(err)=>{
      console.log(err)
    })
  },
  getUserInfo(){
    network.getRequest(config.getInfo,null,(res)=>{
      this.setData({
        user:res.admin
      })
      wx.showToast({
        title: '请先扫描床头二维码',
      })
      setTimeout(() => {
        this.doScan()
      }, 2000);
    },(err)=>{
      console.log(err)
    })
  },
  doScan(){
    let $this=this
    wx.scanCode({
      success (res) {
        $this.setData({
          address:res.result
        })
        wx.setStorageSync('address', res.result)
        wx.setStorageSync('user', $this.data.user)
        $this.fetchCategory()
        $this.judgeUserInfo()
      }
    })
  },
  
  handleClickCategory({currentTarget}){
    var {id}=currentTarget.dataset
    console.log(id)
    this.setData({
      activeIndex:id
    })
    this.fetchProduct()
  },
  fetchCategory:function(){
    network.getRequest(config.categoryList,null,(res)=>{
      if(res.length>0){
        this.setData({
          categories:res,
          activeIndex:res[0].id,
          currentCategory:res[0]
        })
        this.fetchProduct()
      }
      
    })
  },
  fetchProduct:function(){
    network.getRequest(config.productList,{categoryId:this.data.activeIndex},(res)=>{
      console.log(res)
      this.setData({
        products:res
      })
    })
  },
  onSaleNumber(e){
    var number=e.detail
    var {category,product}=e.currentTarget.dataset
    var productData=this.data.products.filter(item=>{
      return item.id===product
    })[0]
    var buyProductMap=this.data.buyProductMap
    var buyProductNumber =this.data.buyProductNumber
    if(buyProductMap[product]){
      buyProductMap[product]={...buyProductMap[product],number:number}
      buyProductNumber[product]=number
    }else{
      buyProductNumber[product]=number
      buyProductMap[product]={
        name:productData.productName,
        id:productData.id,
        price:productData.productShopPrice,
        image:productData.productImg,
        categoryId:productData.productCategoryId,
        number:number
      }
    }
   
    
    console.log(buyProductMap)
    console.log(buyProductNumber)
    var money=0
    for(var item in buyProductMap){
      var data=buyProductMap[item]
      money+=(data.number*data.price)
    }
    this.setData({
      buyProductNumber:buyProductNumber,
      buyTotalMoney:money.toFixed(2)
    })
  },
  doSettlement(){
    var buyProductMap=this.data.buyProductMap
    console.log(buyProductMap)
    var orderProductDtos=[]
    for(var item in buyProductMap){
      var data=buyProductMap[item]
      orderProductDtos.push({
        productId:data.id,
        number:data.number
      })
    }
    var userId=this.data.user.id
    console.log(userId,orderProductDtos)
    network.postRequest(config.createOrder,{
      userId:userId,
      address:this.data.address,
      orderProductDtos:orderProductDtos
    },(res)=>{
      console.log(res)
      wx.showToast({
        title: '订单创建成功！',
      })
      this.setData({
        buyProductMap:{},
        buyTotalMoney:0,
        buyProductNumber:{}
      })
      this.fetchProduct()
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/order/index',
        })
      }, 2000);
    },(err)=>{
      console.log(err)
    })
  }
})